<?php
/**
 * Created by PhpStorm.
 * User: 陈杰
 * QQ:823380606
 * Date: 2019/12/4
 * Time: 22:19
 */

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Api\ExtendGroupModel;

use GatewayClient\Gateway;
use Illuminate\Http\Request;

class ApiGroupController extends Controller
{
    /**
     * 修改群组信息
     */
    public function edit_img(Request $request)
    {
        try {
            $rules = [
                'gid' => 'required|integer|min:1',
                'img' => 'required|min:10|max:255',
            ];
            $sqlmap = self::checkValidate($rules, $request->all(), ['id' => '群组id', 'img' => '群组头像']);
            $model = ExtendGroupModel::find($sqlmap['gid']);
            if (!isset($model) || $model->headman !== $request->get('uid'))
                return self::errorMsg('只有群主才有权限修改');
            $model->img = $sqlmap['img'];
            $model->save();
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function edit_name(Request $request)
    {
        try {
            $rules = [
                'gid' => 'required|integer|min:1',
                'name' => 'required|min:2|max:10',
            ];
            $sqlmap = self::checkValidate($rules, $request->all(), ['id' => '群组id', 'name' => '群名称']);
            $model = ExtendGroupModel::find($sqlmap['gid']);
            if (!isset($model) || $model->headman !== $request->get('uid'))
                return self::errorMsg('只有群主才有权限修改');
            $model->name = $sqlmap['name'];
            $model->save();
            $data = self::creatSystem("修改了群名称为:$model->name");
            //Gateway::sendToAll(json_encode($data, 256));
            Gateway::sendToGroup($sqlmap['gid'], json_encode($data, 256));
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }

    public function edit_content(Request $request)
    {
        try {
            $rules = [
                'gid' => 'required|integer|min:1',
                'content' => 'required|min:2|max:255',
            ];
            $sqlmap = self::checkValidate($rules, $request->all(), ['id' => '群组id', 'content' => '群公告']);
            $model = ExtendGroupModel::find($sqlmap['gid']);
            if (!isset($model) || $model->headman !== $request->get('uid'))
                return self::errorMsg('只有群主才有权限修改');
            $model->content = $sqlmap['content'];
            $model->update_time = time();
            $model->save();
            $data = self::creatSystem($model->content, true);
            Gateway::sendToAll(json_encode($data, 256));
            Gateway::sendToGroup($sqlmap['gid'], json_encode($data, 256));
            return self::successMsg();
        } catch (\Exception $exception) {
            return self::errorMsg($exception->getMessage());
        }
    }


}